<?php

namespace app\common\model;

use think\Db;
use think\Model;


/**
 * 会员模型
 */
class UcenterMember extends Model
{
    /**
     * 数据完成
     * @var array
     */
    protected $auto = [];
    protected $insert = ['status' => 1, 'password', 'password2'];
    protected $update = [];

    protected function setPasswordAttr($value)
    {
        return think_ucenter_md5($value, PASSWORD_KEY);
    }

    protected function setPassword2Attr($value)
    {
        return think_ucenter_md5($value, PASSWORD_KEY);
    }

    /**
     * 三种登录方式验证
     * @param $username
     * @param $password
     * @return int|mixed
     */
    public function login($username, $password)
    {
        /* 获取用户数据 */
        $user = $this->where('mobile', $username)->whereOr('username', $username)->find();
        if (is_object($user) && $user->status >= 0) {
            /* 验证用户密码 */
            if (think_ucenter_md5($password, PASSWORD_KEY) === $user['password']) {
                $this->updateLogin($user['id']); //更新用户登录信息
                return $user['id']; //登录成功，返回用户ID
            } else {
                return -2; //密码错误
            }
        } else {
            return -1; //用户不存在或被禁用
        }
    }

    /**
     * 邮箱登录
     * @param $email
     * @return int
     */
    public function emailLogin($email)
    {
        /* 获取用户数据 */
        $user = $this->where('email', $email)->find();

        if (is_object($user) && $user->status >= 0) {
            $this->updateLogin($user['id']); //更新用户登录信息
            return $user['id']; //登录成功，返回用户ID
        } else {
            return -1; //用户不存在或被禁用
        }
    }

    /**
     * 更新用户登录信息
     * @param  integer $uid 用户ID
     */
    protected function updateLogin($uid)
    {
        $data = array(
            'id' => $uid,
            'last_login_time' => NOW_TIME,
            'last_login_ip' => get_client_ip(1),
        );
        $this->update($data);
        $this->where('id', $uid)->setInc('login_count', 1);
    }

}
